package dk.itu.iwjx.servlet;


import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dk.itu.iwjx.beans.*;
import dk.itu.iwjx.helper.*;


/**
 * Servlet implementation class Main as Controller
 */
public class Main extends HttpServlet {

	private static final long serialVersionUID = 1L;

    public void init(ServletConfig config) throws ServletException
    {
    	super.init(config);

    	DBConnection.dbURL=config.getInitParameter("dbURL")+config.getInitParameter("dbName");
    	DBConnection.dbUserName=config.getInitParameter("dbUserName");
    	DBConnection.dbPassword=config.getInitParameter("dbPassword");
    }
    
	HttpSession session;
	CartBean cart;
	UserBean user;
	ItemBean item;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   
		session = request.getSession();		
		String path = "index.jsp";
		String command = request.getServletPath();
		
		/************ For shopping cart ************/

		cart = new CartBean();

        /*********** user **************************/
	    String name,password;	      	   
		 if(command != null){
			 /************** User profile ****************/
	          if(command.equals("/register.do")){
	        	  if(register(request,response)){
	        		  path="confirmRegister.jsp";
	        		  int code = (int)(Math.random()*8999) + 1000;
	        		  session.setAttribute("code", code);
	        	  }else{
	        		  session.setAttribute("error", "something is wrong!");
	        		  response.sendRedirect("register.jsp");
	        		 
	        	  }	        	  
	           }
	          else if (command.equals("/confirm.do")){
                    if(checkCode(request,response)){
                    	path = "showPizza.jsp";
                    }else{
                    	session.setAttribute("codeIsWrong", "please try again");
                    	path = "confirmRegister.jsp";
                    }
	          }
             else if(command.equals("/login.do")){
        	       name = request.getParameter("name");
    	           password = request.getParameter("password");
    	          
                 // if inputs are valid 
    	        if(name != null && password != null){
    	        	// if it is admin login, hard coded password username
    	        	if(password.equals("admin")&&name.equals("admin")){
    	        		path = "editPizza.jsp";
    	        	}
    	        	else{
	        	        user = new UserBean();
	                    user.setName(name);
	                    user.setPassword(password);
	    	            try {
							user = Factory.instance().getUserHelper().getUser(user);
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	        	        if(user != null ){
	        		    session.setAttribute("user", user); 	
			    		path="showPizza.jsp";
	        	        }else{
	        		       path = "index.jsp"; // password and name not found
	        	         }
    	        	}
        	      }else{
        	    	  path = "index.jsp"; // input value is null
        	      }
	           }
	           else if(command.equals("/logOut.do")){
	        	   session.removeAttribute("user");
	           }
	      /*************** Order Pizza ***************/
	           else if(command.equals("/add.do")){
	        	   addItem(request,response);
	        	   response.sendRedirect("index.jsp");
	           }
	           else if(command.equals("/remove.do")){
	        	   removeItem(request,response);
	        	   response.sendRedirect("index.jsp");
	           }
	           else if(command.equals("/sort.do")){
	        	   sortAllPizza(request,response);
	        	   response.sendRedirect("index.jsp");
	           }
	       /************** admin edit pizza  *********/ 
	           else if(command.equals("/edit.do")){
	        	   
	           }
	           else{	        	   
	        	   path="pageNoFind.jsp";
	           }
        
          }
	
//		 request.getRequestDispatcher(path).forward(request,response) ;
	}	
	
	private boolean checkCode(HttpServletRequest request,
			HttpServletResponse response) {
		String replyCode = request.getParameter("replyCode");	
		int code = (Integer) session.getAttribute("code");
		if( replyCode!= null){
			 int rCode = Integer.parseInt(replyCode) ;
		   if(rCode == code){
			   return true;		   	
		   }
		} 
		return false;
	}

	private boolean register(HttpServletRequest request, HttpServletResponse response){
		
        String name = request.getParameter("name");
		String  email = request.getParameter("email");
		String password = request.getParameter("password");
		String confirmPassword = request.getParameter("confirmPassword");
		String  address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String zipcode = request.getParameter("zipcode");		
		boolean pw = password.equals(confirmPassword); // passwords have to match
		
		if(pw&&name != null && email !=null && password != null && confirmPassword != null
				&& phone != null && zipcode != null && address != null){
			  Validation v = new Validation();
			  int iphone = Integer.parseInt(phone);
			  int izipcode = Integer.parseInt(zipcode);
			  if(v.validateEmail(email)&&v.validateName(name)&&v.validatePassword(confirmPassword)&&
					 v.validatePhone(iphone)&v.validateZipcode(izipcode)){
				  UserBean rUser = new UserBean(); // registering user
				  rUser.setName(name);
				  rUser.setPassword(password);
				  rUser.setAddress(address); 
				  rUser.setPhone(iphone);
				  rUser.setZipcode(izipcode);
				  session.setAttribute("rUser", rUser);
				  return true;
			  }
		}
		return false;
	}
	
	/**
	 * add an item to the shopping cart
	 * @param ib
	 * @throws SQLException 
	 */
	private void addItem(HttpServletRequest request, HttpServletResponse response){
		int id=Integer.parseInt(request.getParameter("id"));
		cart=(CartBean) session.getAttribute("cart");
		Map<Integer,ItemBean> items=(Map<Integer,ItemBean>)cart.getItems();
		
		//check if id already exists, add the quantity if it does
		if(items.containsKey(id)){
			int qua=items.get(id).getQuantity();
			items.get(id).setQuantity(qua+1);
		}else{
			ItemBean item=new ItemBean();
			item.setPizzaId(id);
			item.setQuantity(1);
			items.put(id,item);
		}
		calculateTotal();
	}
	

	/**
	 * remove an item to the shopping cart
	 * @param ib
	 * @throws SQLException 
	 */
	private void removeItem(HttpServletRequest request, HttpServletResponse response){
		int id=Integer.parseInt(request.getParameter("id"));
		cart=(CartBean) session.getAttribute("cart");
		Map<Integer,ItemBean> items=(Map<Integer,ItemBean>)cart.getItems();
		int qua=items.get(id).getQuantity();
		if(qua==1)items.remove(id);
		else items.get(id).setQuantity(qua-1);
		
		calculateTotal();
	}
	
	private void calculateTotal(){
		cart=(CartBean) session.getAttribute("cart");
		Map<Integer,ItemBean> items=(Map<Integer,ItemBean>)cart.getItems();
		
		//get all pizzas again...;
		Map<Integer,PizzaBean> pizzaList =(Map<Integer, PizzaBean>)session.getAttribute("pizzaList");
 		
		float total = 0;
		for(ItemBean ib:items.values()){
			total+=pizzaList.get(ib.getPizzaId()).getPrice()*ib.getQuantity();
		}
		cart.setTotalPrice(Math.round(total));
	}
	
	private void sortAllPizza(HttpServletRequest request, HttpServletResponse response){
		String sortBy=request.getParameter("sortby");
		Map<Integer,PizzaBean> pizzaList =(Map<Integer,PizzaBean>)session.getAttribute("pizzaList");
		List<PizzaBean> sortedPizzaList=new ArrayList<PizzaBean>(pizzaList.values());
		Collections.sort(sortedPizzaList,new SortCriteria(sortBy));
		session.setAttribute("sortedPizzaList", sortedPizzaList);
	}

}


